package com.qf.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.enums.InterfaceExceptionEnums;
import com.qf.exception.SmsException;
import com.qf.model.StandardReport;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/*** @author xl
 * @version V1.0
 * @Project sms_platform
 * @Package com.qf.listener
 * @Description: ${TODO}
 *@Date 2022/8/29 15:53
 */
@Service
@Slf4j
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //日志索引名称
    @Value("${log-index}")
    private String index;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void saveLog(StandardSubmit standardSubmit) throws IOException {
        //1.获取索引名称
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());
        //2.request
        IndexRequest request = new IndexRequest();
        request.index(indexName);
        request.id(standardSubmit.getSequenceId());
        //3.封装
        request.source(objectMapper.writeValueAsString(standardSubmit), XContentType.JSON);
        //4.执行并获取结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        //5.根据结果判断执行是否成功
        String result = response.getResult().toString();
        if (!result.equalsIgnoreCase("created")) {
            log.error("【搜索模块】添加日志 ， 添加日志失败！！ result = {},submit = {}", result, standardSubmit);
            throw new SmsException(InterfaceExceptionEnums.SEARCH_SAVE_LOG_ERROR);
        }
    }

    /**
     *      修改
     * @param report
     * @throws Exception
     */
    @Override
    public void updateLog(StandardReport report) throws IOException {
        //1.获取索引名称
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());
        //2.request  第一个参数：索引名称  第二个参数：修改的id
        UpdateRequest request = new UpdateRequest();
        request.index(indexName);
        request.id(report.getSequenceId());
        //3.封装
        Map<String, Object> source = new HashMap<>();
        source.put("reportState", report.getState());
        source.put("errorCode", report.getErrorCode());
        request.doc(source);
        //4.执行并获取结果
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        //5.根据结果判断执行是否成功
        String result = response.getResult().toString();
        if (!result.equalsIgnoreCase("created")) {
            log.error("【搜索模块】修改日志 ， 修改日志失败！！ result = {},submit = {}", result, report);
            throw new SmsException(InterfaceExceptionEnums.SEARCH_UPDATE_LOG_ERROR);
        }
    }

    /**
     * 查询Es中的日志信息条数
     *
     * @param parameter
     * @return
     * @throws Exception
     */
    @Override
    public Long searchLogCount(Map parameter) throws IOException {
        SearchResponse response = getSearchResponse(parameter);
        long count = response.getHits().getTotalHits().value;
        return count;
    }

    private SearchResponse getSearchResponse(Map parameter) throws IOException {
        //1.获取索引名称
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());
        SearchRequest request = new SearchRequest();
        request.indices(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //获取客户id
        Integer clientID = (Integer) parameter.get("clientID");
        if (clientID != null) {
            boolQuery.must(QueryBuilders.termQuery("clientID", clientID));
        }
        //keyword关键字
        String keyword = (String) parameter.get("keyword");
        if (!StringUtils.isEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("messageContent", keyword));
        }
        //手机号
        String mobile = (String) parameter.get("mobile");
        if (!StringUtils.isEmpty(mobile)) {
            boolQuery.must(QueryBuilders.termQuery("destMobile", mobile));
        }
        //startTime开始时间，endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if (startTime != null) {
            rangeQuery.gte(startTime);
        }
        if (endTime != null) {
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        searchSourceBuilder.query(boolQuery);
        //设置分页
        Integer start = (Integer) parameter.get("start");
        Integer rows = (Integer) parameter.get("rows");
        searchSourceBuilder.from(start);  //当前页  起始索引
        searchSourceBuilder.size(rows);
        //设置高亮信息
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("messageContent");
        highlightBuilder.preTags((String) parameter.get("highLightPreTag"));
        highlightBuilder.postTags((String) parameter.get("highLightPostTag"));
        searchSourceBuilder.highlighter(highlightBuilder);
        request.source(searchSourceBuilder);
        return restHighLevelClient.search(request, RequestOptions.DEFAULT);
    }

    /**
     * 查询Es中的日志信息
     *
     * @param parameter
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> searchLog(Map parameter) throws IOException {
        SearchResponse response = getSearchResponse(parameter);
        List<Map> data = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> source = hit.getSourceAsMap();
            //高亮显示的数据
            HighlightField highlightField = hit.getHighlightFields().get("messageContent");
            if (highlightField != null) {
                String messageContent = highlightField.fragments()[0].string();
                source.put("messageContent", messageContent);
            }
            data.add(source);
        }
        return data;
    }

    /**
     * 统计短信发送状态
     *
     * @param parameter
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Long> statSendStatus(Map parameter) throws IOException {

        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());
        SearchRequest request = new SearchRequest(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置聚合函数  histogram  直方图
        searchSourceBuilder.aggregation(AggregationBuilders.histogram("agg").field("reportState").interval(1));
        //设置查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        Integer clientID = (Integer) parameter.get("clientID");
        if (clientID != null) {
            boolQuery.must(QueryBuilders.termQuery("clientID", clientID));
        }
        //startTime开始时间   endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if (startTime != null) {
            rangeQuery.gte(startTime);
        }
        if (endTime != null) {
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        searchSourceBuilder.query(boolQuery);
        request.source(searchSourceBuilder);
        //4.执行并获取返回结果
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Histogram agg = aggregations.get("agg");
        List<? extends Histogram.Bucket> buckets = agg.getBuckets();
        //5.封装数据
        Map<String, Long> data = new HashMap<>();
        for (Histogram.Bucket bucket : buckets) {
            Double key = (Double) bucket.getKey();
            if (key == 0.0) {
                //短信发送成功
                data.put("0", bucket.getDocCount());
            } else if (key == 1.0) {
                //短信发送失败
                data.put("1", bucket.getDocCount());
            } else {
                //短信未返回状态
                data.put("2", bucket.getDocCount());
            }
        }
        return data;
    }
}
